package com.xsky.common.util;

import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.basic.DateConverter;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.xsky.converter.TimeStampConverter;
import com.xsky.converter.XStreamClobConverter;

public class XMLConverter {

	@SuppressWarnings("unchecked")
	public static <T> T convertToObject(String xmlStr, Class<T> beanClass) {

		try {
			Document document = DocumentHelper.parseText(xmlStr);
			xmlStr = document.selectSingleNode("//data//item").asXML();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		XStream xs = new XStream(new DomDriver());
		String defaultFormat = "yyyy-MM-dd";
		String[] acceptableFormat = { "yyyy-MM-dd HH:MM:SS[.fffffffff]", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd", "yyyy-MM" };
		xs.registerConverter(new DateConverter(defaultFormat, acceptableFormat));
		xs.registerConverter(new XStreamClobConverter());
		xs.registerConverter(new TimeStampConverter());
		xs.alias("item", beanClass);
		T entity = (T) xs.fromXML(xmlStr);

		return entity;
	}

	public static String convertToXML(Object... objects) {
		if (objects == null || objects.length == 0) {
			return "";
		}
		Class<?> clazz = objects[0].getClass();
		String result = "<data>";
		XStream xs = new XStream(new DomDriver());
		String defaultFormat = "yyyy-MM-dd";
		String[] acceptableFormat = { "yyyy-MM" };
		xs.registerConverter(new DateConverter(defaultFormat, acceptableFormat));
		xs.registerConverter(new XStreamClobConverter());
		xs.alias("item", clazz);
		for (Object obj : objects) {
			result += xs.toXML(obj);
		}
		result += "</data>";
		return result.replace("00:00:00.0", "");
	}

	public static String convertToXML(List<?> list) {
		return convertToXML(list.toArray());
	}
	
	public static PageInfo convertToPageInfo(String xml){
		XStream xs = new XStream(new DomDriver());
		xs.alias("pageInfo", PageInfo.class);
		PageInfo entity = (PageInfo) xs.fromXML(xml);
		return entity;
	}
}

